<template>
    <div class="container">
        <Breadcrumb :items="['menu.common', 'menu.common.banner']" />
        <a-card :title="$t('menu.common.banner')">

            <a-space fill direction="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-space fill>
                            <a-button type="primary" @click="openModal()" shape="round">
                                <template #icon><icon-plus /></template>
                                添加轮播图
                            </a-button>
                        </a-space>

                    </a-col>
                    <a-col :flex="1">
                        <a-space align="end" style="justify-content: flex-end;" fill>
                            <a-button shape="circle">
                                <template #icon><icon-refresh /></template>
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>


                <a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
                    @page-change="onPageChange" @page-size-change="onPageSizeChange">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80" />
                        
                        <a-table-column title="图片" data-index="image" :width="200">
                            <template #cell="{ record }">
                                <a-image :src="record.image_url" width="100" />
                            </template>
                        </a-table-column>
                        <a-table-column title="标题" data-index="title" />
                        <a-table-column title="链接" data-index="path" :width="200" />
                        <a-table-column title="创建时间" data-index="created_at" :width="180" />
                        <a-table-column title="排序" data-index="sort_by" :width="100" />
                        <a-table-column title="操作" align="center" :width="120">
                            <template #cell="{ record }">
                                <a-space size="mini">
                                    <a-link  @click="openModal(record)">
                                        编辑
                                    </a-link>
                                    <a-popconfirm position="left" content="确定要删除这个轮播图吗？" @ok="handleDelete(record.id)">
                                        <a-link >
                                            删除
                                        </a-link>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </a-space>
        </a-card>

        <a-modal v-model:visible="modalVisible" :title="formData.id ? '编辑轮播图' : '添加轮播图'" @before-ok="handleSubmit"
            @cancel="closeModal">
            <a-form :model="formData" ref="formRef" layout="vertical">
                <a-form-item field="title" label="标题" :rules="[{ required: true }]">
                    <a-input v-model="formData.title" placeholder="请输入标题" />
                </a-form-item>
                <a-form-item label="图片" :rules="[{ required: true }]">

                    <a-upload list-type="picture" v-model="formData.image" :custom-request="handleUpload" :limit="1"
                        :file-list="fileList" image-preview @before-remove="beforeRemove"/>
                    <template #extra>
                        <div>请保持图片比例为16:9</div>
                    </template>
                </a-form-item>
                <a-form-item field="path" label="链接">
                    <a-input v-model="formData.path" placeholder="请输入链接" />
                </a-form-item>
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item field="type" label="类型">
                            <a-select v-model="formData.type" placeholder="请选择类型">
                                <a-option value="index">小程序首页顶部</a-option>
                                <a-option value="store">严选首页</a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item field="sort_by" label="排序">
                    <a-input-number v-model="formData.sort_by" placeholder="请输入排序" />
                </a-form-item>
                    </a-col>
                </a-row>
                
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { UploadRequest, RequestOption } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryBannerList, submitBannerForm, delBanner, BannerRecord, BannerModel } from '@/api/banner';
import { uploadFile } from '@/api/upload';

const { loading, setLoading } = useLoading(true);
const modalVisible = ref(false);
const formRef = ref();
const fileList = ref<{ url: string }[]>([]);

const basePagination = {
    current: 1,
    pageSize: 10,
    total: 0,
};

const pagination = reactive({
    ...basePagination,
});


const generateFormData = () => {
    return {
        id: 0,
        title: '',
        image: '',
        path: '',
        sort_by: 0,
        type: 'store',
    };
};

const formData = ref(generateFormData());

const renderData = ref<BannerRecord[]>([]);

const fetchData = async () => {
    setLoading(true);
    try {
        const { data } = await queryBannerList({
            page: pagination.current,
            pageSize: pagination.pageSize,
        });
        renderData.value = data.list;
        pagination.total = data.total;
    } catch (err) {
        Message.error('获取Banner列表失败');
    } finally {
        setLoading(false);
    }
};

const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
};

const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
};

const openModal = (record?: BannerRecord) => {
    if (record) {
        formData.value = {
            id: record.id,
            title: record.title,
            image: record.image,
            path: record.path,
            sort_by: record.sort_by,
        };
        fileList.value = [{ url: record.image_url }];
    } else {
        formData.value = generateFormData();
        fileList.value = [];
    }
    modalVisible.value = true;
};

const closeModal = () => {
    modalVisible.value = false;
    formData.value = generateFormData();
};

const handleUpload = async (option: any) => {
    try {
        const { onProgress, onError, onSuccess, fileItem, name } = option;

        const uploadFormData = new FormData();
        uploadFormData.append('file', fileItem.file);
        const { data } = await uploadFile(uploadFormData);
        formData.value.image = data.path;
        fileList.value = [{ url: data.url }];
        Message.success('上传成功');
        return {
            abort: () => { },
        };
    } catch (err) {
        Message.error('上传失败');
        return {
            abort: () => { },
        };
    }
};

const beforeRemove = (file: any) => {
    formData.value.image = '';
    fileList.value = [];
    return true;
};

const handleSubmit = async (done: any) => {
    setLoading(true);
    try {
        await submitBannerForm(formData.value).then((res) => {
            Message.success(res.msg || '操作成功');
            closeModal();
            fetchData();
            done(true);
        });
    } catch (err) {
        // you can report use errorHandler or other
        done(false);
    } finally {
        setLoading(false);
    }
};

const handleDelete = async (id: number) => {
    try {
        await delBanner(id);
        Message.success('删除成功');
        fetchData();
    } catch (err) {
        Message.error('删除失败');
    }
};

onMounted(() => {
    fetchData();
});
</script>

<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;
}
</style>

<script lang="ts">
export default {
    name: 'CommonBanner',
};
</script>